package com.zj.core.base

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.view.View
import com.dialogutils.DialogUtils
import com.bletoothutils.BleToothKitUtil
import com.fileutils.StringUtils
import com.dialogutils.ToastUtil
import com.zj.core.services.BleToothService.Companion.mConnectStatus
import org.greenrobot.eventbus.EventBus
import com.zj.core.services.BleToothService
import com.zj.core.bean.EventBusMessage
import com.zj.core.R
import com.zj.core.tools.Constant
import org.greenrobot.eventbus.Subscribe
import com.zj.core.bean.DeviceValue
import com.zj.core.bean.EventBusMessage.Companion.BLUE_TOOTH_DATA_TAG
import com.zj.core.bean.EventBusMessage.Companion.BLUE_TOOTH_STATUS_TAG
import com.dialogutils.LoadingAlertDialog
import com.moduleinterface.IStatus.*
import com.moduleinterface.InterfaceFactory
import com.zj.core.bean.EventBusMessage.Companion.BLUE_TOOTH_IS_CONNECT_FAILE
import com.zj.core.bean.EventBusMessage.Companion.BLUE_TOOTH_IS_CONNECT_OK
import com.zj.core.bean.EventBusMessage.Companion.BLUE_TOOTH_IS_FAILE
import com.zj.core.bean.EventBusMessage.Companion.BLUE_TOOTH_IS_OPEN
import com.zj.core.bean.EventBusMessage.Companion.BLUE_TOOTH_IS_SEACH_CANCEL
import com.zj.core.bean.EventBusMessage.Companion.BLUE_TOOTH_IS_SEACH_IN
import com.zj.core.bean.EventBusMessage.Companion.BLUE_TOOTH_IS_SEACH_STOP

/**
 * 日期：2019年6月20日
 * 公司：北京子杰宝贝科技有限公司
 * 地址：北京市朝阳区朝阳农场
 * 开发者：达选文
 * <p>
 * 主体功能：数据录入界面蓝牙功能
 */
@SuppressLint("Registered")
open class BaseBleToothActivity: BaseRecordActivity(),View.OnClickListener{
    private var ScanActivityRequestCode=1           //扫码后返回
    private var ScanActivityResultCode = 2
    private var mHandler: RecordHandler? = null

    companion object{
        var mDevBean: DeviceValue? = null                  //成人身高体重秤
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mHandler= RecordHandler()
        EventBus.getDefault().register(this)

        if (mConnectStatus) {
            view.recordConnectDevice.text = "断开"
        } else {
            view.recordConnectDevice.text = "设备"
        }
    }

    /**
     * 扫描设备条码进行连接
     */
    override fun connectDevice(){
        if (!mConnectStatus) {
            /**
             * 判断蓝牙是否打开
             */
            if (BleToothKitUtil.bleCheckAndListener(this)){
                //cacheInputData(record_input_view_tv.text.toString())
                InterfaceFactory.getInstance().getmInterfaceQR().scanQRcode(this,"设备",2)
            } else {
                ToastUtil.showShort(this, "请先打开蓝牙")
            }
        } else {
            DialogUtils.create(this, null, "确认断开连接？", "断开",
                mViewListener, "取消", mViewListener, true, true,
                false
            ).show()
        }
    }

    /**
     * 条码扫描返回
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?){
        super.onActivityResult(requestCode, resultCode, data)
        when(requestCode){
            ScanActivityRequestCode->{                       //条码识别
                if(resultCode== ScanActivityResultCode){                //条码识别返回
                    checkScanCode(data?.getStringExtra("barcode").toString())
                }
            }
        }
    }

    /**
     * 检查扫描返回的条码信息
     */
    private fun checkScanCode(code:String){
        with(StringUtils.replaceBlank(code)){
            val mes = Message()
            if (substring(0, 4) == "@CH@"&& substring(length - 1,length) == "@") {       //成人身高体重秤
                substring(4,length - 1).split(":".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray().apply {
                    if (this[1].substring(this[1].length - 1, this[1].length) == "H") {
                        val mDeviceBean = DeviceValue()
                        mDeviceBean.setmType("成人身高体重")
                        mDeviceBean.setmHight(java.lang.Float.parseFloat(this[2]))
                        mDeviceBean.setmWeight(java.lang.Float.parseFloat(this[1].substring(0, this[1].length - 1)))
                        mes.what = STATUS_RECORD_DATA_OK
                        mes.obj = mDeviceBean
                    } else {
                        mes.what = STSTUS_RECORD_DATA_ERROR
                    }
                }
            } else if (length == 17 && substring(0, 1) == "@" && substring(3, 4) == "@"
                && substring(length - 1, length) == "@"){        //其他医疗设备
                mes.what = STATUS_RECORD_BARCODE
                mes.obj = code
            } else {
                mes.what = STATUS_RECORD_NOALLOW
            }
            mHandler?.sendMessage(mes)
        }
    }

    /**
     * 蓝牙设备Handler
     */
    class RecordHandler : android.os.Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                /**
                 * 蓝牙设备数据
                 */
                STSTUS_RECORD_DATA_ERROR-> ToastUtil.showShort(BaseApplication.context, "数据格式有误")
                STATUS_RECORD_DATA_OK-> mDevBean = msg.obj as DeviceValue?
                STATUS_RECORD_BARCODE-> {                                //连接设备
                    BaseBleToothActivity().connectBle(msg.obj as String)
                }
                STATUS_RECORD_NOALLOW-> ToastUtil.showShort(BaseApplication.context, "抱歉，该设备暂不允许接入")
            }
        }
    }

    /**
     * eventBus事件
     */
    @Subscribe
    open fun onEventBus(mes: EventBusMessage){
        when(mes.keycode){
            EventBusMessage.PHOTO_CUT_TAG ->                                              //裁剪后图片地址返回
                ToastUtil.showShort(this, Constant.fileSavePath(this, "").path)

            EventBusMessage.BLUE_TOOTH_TITLE_TAG ->                                        //按钮状态数据返回
                view.recordConnectDevice.text=mes.mes

            BLUE_TOOTH_DATA_TAG->{                                        //蓝牙数据回调
                if (!mes.mes.isBlank()) {
                    voiceResourceResult(mes.mes)
                }
            }

            BLUE_TOOTH_STATUS_TAG->{                                           //蓝牙状态回调
                if(mes.notify!=0){
                    bleToothConnectStatus(mes.notify)
                }

                if (!mes.mes.isBlank()){
                    view.recordConnectDevice.text = mes.mes
                }
            }
        }
    }

    /**
     * 数据录入
     */
    open fun voiceResourceResult(mes:String){}

    /**
     * 蓝牙连接状态
     * @param status
     */
    private fun bleToothConnectStatus(status: Int) {
        when (status) {
            BLUE_TOOTH_IS_OPEN -> ToastUtil.showShort(BaseApplication.context, "蓝牙已打开")
            BLUE_TOOTH_IS_FAILE -> ToastUtil.showShort(BaseApplication.context, "蓝牙打开失败")
            BLUE_TOOTH_IS_SEACH_IN -> LoadingAlertDialog.getInstance(this).show("连接中...")
            BLUE_TOOTH_IS_SEACH_STOP -> LoadingAlertDialog.getInstance(this).dismiss()
            BLUE_TOOTH_IS_SEACH_CANCEL -> ToastUtil.showShort(BaseApplication.context, "已取消搜索")
            BLUE_TOOTH_IS_CONNECT_OK -> LoadingAlertDialog.getInstance(this).dismiss()
            BLUE_TOOTH_IS_CONNECT_FAILE -> LoadingAlertDialog.getInstance(this).dismiss()
        }
    }

    /**
     * 断开设备事件监听
     */
    private var mViewListener: View.OnClickListener = View.OnClickListener { v ->
        when (v.id){
            R.id.common_dialog_cancel_tv -> { }

            R.id.common_dialog_confirm_tv -> {
                mConnectStatus = false
                disConnectBle(BleToothService.mConnectMac.toString())
            }
        }
    }

    override fun onDestroy(){
        super.onDestroy()

        LoadingAlertDialog.getInstance(this).destory()

        if(mHandler!=null){
            mHandler=null
        }
        if(mDevBean !=null){
            mDevBean =null
        }
        EventBus.getDefault().unregister(this)
        InterfaceFactory.getInstance().getmInterfaceQR().destroyQR()
    }
}